import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;


public class Open extends JComponent{
	
	private String extension;
	private JFileChooser fc;
	private Image newImage;
	
	//Constructor
	Open(String ext){
		extension = ext;
	}
	
	public Image openImage(){
		
		
		//File chooser
		fc = new JFileChooser();
		fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		//setBMP
		FileFilter type = new ExtensionFilter("Image file", "." + extension);
		fc.addChoosableFileFilter(type);
		int returnVal = fc.showOpenDialog(this);		
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fc.getSelectedFile();
            //Check if overwriting is needed
            if(selectedFile.exists()){
    	            	try {
        	                newImage = ImageIO.read(selectedFile);
	        	         } 
	        	    	 catch(IOException e) {
	        	            	JOptionPane.showMessageDialog(this, "Read error for " + selectedFile.getPath() + ": " + e.getMessage(), "Unable to open file", JOptionPane.ERROR_MESSAGE);
	        	         }
    	     }
    	     else{
    	    	 JOptionPane.showMessageDialog(this, "File does not exist", "Unable to open file", JOptionPane.ERROR_MESSAGE);
    	    	 return null;
    	     }
        } 
        else {
            //user canceled
        	return null;
        }
        return newImage;
        
	}

}
